package com.aditya.videoutil;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CompressVideoActivity extends VideoActivity {
  private int count;
  private Bitmap[] thumbnails;
  private boolean[] thumbnailsselection;
  private String[] arrPath;
  private VideoAdapter imageAdapter;
  private Cursor videoCursor;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compress_video);
    new PickingImage().execute();
  }

  public class VideoAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public VideoAdapter() {
      mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
      return count;
    }

    public Object getItem(int position) {
      return position;
    }

    public long getItemId(int position) {
      return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      if (convertView == null) {
        holder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.galleryitem, null);
        holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
        holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
        holder.textView = (TextView) convertView.findViewById(R.id.videoFileName);

        convertView.setTag(holder);
        convertView.setBackgroundColor(getResources().getColor(R.color.lavendar_pinochio));
      } else {
        holder = (ViewHolder) convertView.getTag();
      }
      holder.checkbox.setId(position);
      holder.imageview.setId(position);
      holder.textView.setId(position);
      holder.checkbox.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
          // TODO Auto-generated method stub
          CheckBox cb = (CheckBox) v;
          int id = cb.getId();
          if (thumbnailsselection[id]) {
            cb.setChecked(false);
            thumbnailsselection[id] = false;
          } else {
            cb.setChecked(true);
            thumbnailsselection[id] = true;
          }
        }
      });

      int width = getWindowManager().getDefaultDisplay().getWidth() * 2 / 5;
      if (thumbnails[position] != null) {
        Bitmap resizedbitmap = Bitmap.createScaledBitmap(thumbnails[position], width, width, true);
        holder.imageview.setImageBitmap(resizedbitmap);
      } else {
        holder.imageview.setImageResource(R.drawable.video_thumbnail);
      }

      holder.checkbox.setChecked(thumbnailsselection[position]);
      holder.textView.setText(arrPath[position].substring(arrPath[position].lastIndexOf("/") + 1));
      holder.id = position;
      return convertView;
    }
  }

  class ViewHolder {
    ImageView imageview;
    CheckBox checkbox;
    TextView textView;
    int id;
  }

  private class PickingImage extends AsyncTask<String, Void, Boolean> {

    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
      progressDialog = new ProgressDialog(CompressVideoActivity.this);
      progressDialog.setMessage("Collecting videos from phone...");
      progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
      progressDialog.show();

    }

    @Override
    protected void onPostExecute(Boolean result) {
      if (progressDialog != null && progressDialog.isShowing())
        progressDialog.dismiss();
      showVideos();
    }

    @Override
    protected Boolean doInBackground(String... params) {
      final String[] columns = { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID };
      final String orderBy = MediaStore.Video.Media._ID;
      videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
      int image_column_index = videoCursor.getColumnIndex(MediaStore.Video.Media._ID);
      count = videoCursor.getCount();
      thumbnails = new Bitmap[count];
      arrPath = new String[count];
      thumbnailsselection = new boolean[count];
      for (int i = 0; i < count; i++) {
        videoCursor.moveToPosition(i);
        int id = videoCursor.getInt(image_column_index);
        int dataColumnIndex = videoCursor.getColumnIndex(MediaStore.Video.Media.DATA);
        thumbnails[i] = MediaStore.Video.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id,
            MediaStore.Video.Thumbnails.MINI_KIND, null);
        arrPath[i] = videoCursor.getString(dataColumnIndex);
      }

      return true;
    }
  }

  public void showVideos() {
    GridView imagegrid = (GridView) findViewById(R.id.videoGrid);
    imageAdapter = new VideoAdapter();
    imagegrid.setAdapter(imageAdapter);
    if (videoCursor != null) {
      videoCursor.close();
    }

    final Button selectBtn = (Button) findViewById(R.id.selectBtn);
    selectBtn.setOnClickListener(new OnClickListener() {

      public void onClick(View v) {
        final int len = thumbnailsselection.length;
        ArrayList<String> selectedVideos = new ArrayList<String>();
        for (int i = 0; i < len; i++) {
          if (thumbnailsselection[i]) {
            selectedVideos.add(arrPath[i]);
          }
        }
        if (selectedVideos.size() < 2) {
          Toast.makeText(getApplicationContext(), "Please select at least 2 videos!", Toast.LENGTH_LONG).show();
        } else {
          Toast.makeText(getApplicationContext(), "You selected " + selectedVideos.size() + " videos - Get Set!!!",
              Toast.LENGTH_LONG).show();
          concatenate(selectedVideos);

        }
      }
    });

  }

  protected void concatenate(ArrayList<String> selectedVideos) {
    Intent intent = new Intent(this, OutputActivity.class);
    intent.putStringArrayListExtra("MERGE", selectedVideos);
    startActivity(intent);
  }

}
